package org.ezplatform.office.forum.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;
import javax.transaction.Transactional;

import org.ezplatform.cloud.api.system.user.UserApiService;
import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.forum.dao.ForumTypeDao;
import org.ezplatform.office.forum.entity.ForumType;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @desc 论坛类别Service
 * @create 2017-11-15 10:16
 **/
@Service
@Transactional
public class ForumTypeService extends BaseService<ForumType, String> {

    private final Logger LOGGER = LoggerFactory.getLogger(ForumTypeService.class);

    @Autowired
    private ForumTypeDao forumTypeDao;

    @Autowired
    private UserApiService userApiService;
    
    @Autowired
	private LogService logService;

    @Override
    protected JpaBaseDao<ForumType, String> getEntityDao() {
        return forumTypeDao;
    }

    public boolean checkCodeUnique(ForumType entity) {
        boolean flag = false;
        if(StringUtils.isEmpty(entity.getCode()))   return flag;

        if(StringUtils.isEmpty(entity.getId())){
            // 新增情况下的编码校验
            StringBuffer sql = new StringBuffer();
            sql.append(" select count(1) from oa_forum_type where code = ? and is_delete = 0 ");
            Query query =  getEntityManager().createNativeQuery(sql.toString()).setParameter(1, entity.getCode());
            int count = Integer.parseInt(query.getSingleResult().toString());
            if(count == 0){
                flag = true;
            }
        } else {
            // 编辑情况下的编码校验
            StringBuffer sql = new StringBuffer();
            sql.append(" select count(1) from oa_forum_type where code = ?1  and id != ?2 and is_delete = 0 ");
            Query query =  getEntityManager().createNativeQuery(sql.toString())
                    .setParameter(1, entity.getCode())
                    .setParameter(2,entity.getId());
            int count = Integer.parseInt(query.getSingleResult().toString());
            if(count == 0){
                flag = true;
            }
        }

        return flag;
    }

    
    public boolean ifDelete(String id) {
    	StringBuffer sql = new StringBuffer();
    	sql.append(" select count(*) from oa_forum_board where forum_type = :id  AND is_delete = '0' ");
    	Query query =  this.getEntityManager().createNativeQuery(sql.toString());
    	query.setParameter("id",id);
    	int count = Integer.parseInt(query.getSingleResult().toString());
    	if(count==0) {
    		return true;
    	}else {
    		return false;
    	}
    	
    }
    
    /**
     * 
     * @Title: checkDelete
     * @Description: 类别删除前的能否校验：当类别下有版块时不能删除
     *     
     * @param ids
     * @return 
     * @return: boolean
     *
     * @date 2017年11月17日 下午3:54:14
     *
     */
	public boolean checkDelete(String[] ids) {
		LOGGER.info(ids.toString());
		boolean flag = false;
		StringBuffer sql = new StringBuffer();
		sql.append(" select count(1) from oa_forum_board a where a.forum_type in (:ids) and a.is_delete = 0 ");
		Query query =  this.getEntityManager().createNativeQuery(sql.toString());
		List<String> idlist = Arrays.asList(ids);
        query.setParameter("ids", idlist); 
        int count = Integer.parseInt(query.getSingleResult().toString());
        if(count == 0){
            flag = true;
        }
        
        return flag;
	}

    /**
     *
     * @Title: findPage
     * @Description:
     *     根据分页获取类型
     * @param pageable
     * @param filter
     * @param corpId
     * @return
     * @return: List<Map>
     *
     * @date 2017年11月24日 下午6:41:08
     *
     */
    public Page<Map> findPage(Pageable pageable, List<PropertyFilter> filter, String corpId, String token) {
        StringBuffer sql = new StringBuffer();
        Map<String, Object> values = new HashMap<String, Object>();
        sql.append(" select a.id, a.name, a.code, a.createdDate, a.createdBy, a.createdName, a.sortNo, a.status  from ( ");
        sql.append(" select t.id, t.name, t.code, t.createdDate, t.createdBy, x.userName as createdName, t.sort_no as sortNo, t.status ");
        sql.append(" from oa_forum_type t ");
        sql.append(" left join  ");
        sql.append(" (select u.id, u.user_name as userName from sys_user u where ");
        //sql.append(" u.is_delete = 0 and ");
        sql.append(" u.corp_id = :corpId ");
        sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
        sql.append(" on x.id = t.createdBy ");
        sql.append(" where t.corp_id = :corpId and t.is_delete = 0 ");
        sql.append(" ) a where 1 = 1");
        values.put("corpId", corpId);
        String s = sql.toString();
        s = PropertyFilter.getSqlByFilterAndPageable("a", s, "a.sortNo, a.createdDate desc", filter, pageable);
        Page<Map> page = super.findByPageNativeSQL(pageable, s, values);
//        findPageListCreatedName(page, token, corpId, "createdBy", "createdName");

        return page;
    }

    /**
     *
     * @Title: logicDelete
     * @Description:
     *     逻辑删除信息
     * @param ids
     *
     * @return: boolean
     *
     * @date 2017年12月7日 下午12:36:37
     *
     */
    public OperationResult logicDelete(String[] ids) {
        LOGGER.info("开始删除论坛类别信息");
        List idList = Arrays.asList(ids);
        WebUser user = WebUtils.getCurrentUser();
        Iterator it0 = idList.iterator();
        List<String> error = new ArrayList<String>();

        while (it0.hasNext()){
            String id =  it0.next().toString();
            if(StringUtils.isNotBlank(id)) {
                String s1 = "UPDATE oa_forum_type set is_delete = 1 where id = :id ";
                try {
                    int n = this.getEntityManager().createNativeQuery(s1).setParameter("id", id)
                            .executeUpdate();
                    ForumType f = forumTypeDao.getOne(id);
                    if (n <= 0) {
                        error.add(id);
                        logService.saveModuleLog("forum:type:04", f.getName(), "",UuidUtils.UUID()); 
                    }else {
                    	logService.saveModuleLog("forum:type:04", f.getName(), ""); 
                    }
                } catch (Exception e) {
                    LOGGER.error(e.getMessage());
                    error.add(id);
                }
            }
        }
        LOGGER.info("结束删除论坛类别信息，预计删除"+ids.length+"条记录，成功"+(ids.length - error.size())+"条，失败"+(ids.length - error.size())+"条");

        if(ids.length == 0){
        	Map resources = new HashMap();
        	//国际化资源
    		resources.put("i18NCode", "oa.forum.seldata");
            return OperationResult.buildFailureResult("请选择相关数据",resources);
        } else {
            if(error.size() > 0){
                return error.size() == ids.length  ? OperationResult.buildFailureResult("删除失败")
                        : OperationResult.buildWarningResult("删除操作已处理. 成功:" + (ids.length - error.size()) + "条,失败:" + error.size() + "条", error);
            } else {
            	Map resources = new HashMap();
            	//国际化资源
        		resources.put("i18NCode", "oa.forum.deletetips4");
                return ids.length  == 1 ? OperationResult.buildSuccessResult("删除成功",resources)
                        : OperationResult.buildSuccessResult("删除成功",resources);
            }
        }

    }

    public List<ForumType> findAllLabel(String corpId) {
        String s = "select f from ForumType f where f.status = ?1 and f.isDelete = ?2 and f.corpId = ?3 order by f.sortNo, f.createdDate desc ";
        return this.getEntityManager().createQuery(s)
                .setParameter(1, 1)
                .setParameter(2, 0)
                .setParameter(3, corpId)
                .getResultList();
    }

    /**
     * 分页结果拼装 创建人姓名
     * @param page
     * @param token
     * @param corpId
     * @param idFieldName
     * @param nameFieldName
     */
    private void findPageListCreatedName(Page<Map> page, String token, String corpId, String idFieldName, String nameFieldName){
        List<String> ids = new ArrayList<String>();
        String nameField = StringUtils.isNotBlank(nameFieldName) ? nameFieldName : "createdName";
        String idField = StringUtils.isNotBlank(idFieldName) ? idFieldName : "createdBy";

        Iterator it = page.getContent().iterator();
        while(it.hasNext()){
            Map m = (Map) it.next();
            if(!StringUtils.equals(StringUtils.null2String(m.get(idField)), "1")) {
                ids.add(StringUtils.null2String(m.get(idField)));
            }
        }

        Map<String,String> textParams = new HashMap<String,String>();
        textParams.put("corpId", corpId);
        textParams.put("id", StringUtils.join(ids, ","));
        List<Map<String,Object>> userMap = userApiService.getUserRelatedInfo(StringUtils.join(ids, ","),"", corpId, token);

        it = page.getContent().iterator();
        while(it.hasNext()){
            Map m = (Map) it.next();
            if(StringUtils.equals(StringUtils.null2String(m.get(idField)), "1")){
                m.put(nameField, "系统管理员");
            } else {
            	if (userMap != null && userMap.size() > 0) {
            		m.put(nameField, userMap.get(0).get(StringUtils.null2String(m.get(idField)) + "user"));
            	}
            }

        }
    }
    
    /**
	 * 所有帖子页面获取类别
	 * @param user
	 * @return
	 */
    public List<Map> getTypeMap(){
        StringBuffer sql = new StringBuffer();
		sql.append(" SELECT id,name,createdDate from oa_forum_type t WHERE t.status = 1 AND t.is_delete = 0 ORDER BY createdDate DESC");
		List<Map> list = super.findByListNativeQuery(sql.toString(), null);
		return list;
    }
    
	  /**
	    * 保存操作日志(异步请求)
	    * @param msgType
	    * @param corpId
	    * @param token
	    */
	  @Async
	  public void saveModuleLog(String code,String title,String value) {
		  logService.saveModuleLog(code, title, value);
	  }
}
